package com.yuewen.mall.common.hibernater;

import org.hibernate.Query;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import java.math.BigInteger;
import java.util.List;

/**
 * Created by liwei.b on 2016/6/17.
 */
public class BaseDao extends HibernateDaoSupport {
    public <T> T getById(BigInteger id, Class<T> entityClass) {
        String lsql = String.format("from %s where id=:id", getClassNameOnly(entityClass));
        Query query = HibernateSessionFactory.getSession().createQuery(lsql);
        query.setBigInteger("id", id);
        List<T> results = query.list();
        if (results.size() <= 0) {
            return null;
        }
        return (T) results.get(0);
    }

    public <T> List<T> getAll(Class<T> entityClass) {
        String lsql = String.format("from %s", getClassNameOnly(entityClass));
        Query query = HibernateSessionFactory.getSession().createQuery(lsql);
        List<T> results = query.list();
        if (results.size() <= 0) {
            return null;
        }
        return results;
    }

    public <T> List<T> getAll(Class<T> entityClass, String orderBy) {
        String lsql = String.format("from %s order by %s", getClassNameOnly(entityClass), orderBy);
        Query query = HibernateSessionFactory.getSession().createQuery(lsql);
        List<T> results = query.list();
        if (results.size() <= 0) {
            return null;
        }
        return results;
    }

    public <T> List<T> getByPage(Class<T> entityClass, String orderBy) {
        String lsql = String.format("from %s order by %s", getClassNameOnly(entityClass), orderBy);
        Query query = HibernateSessionFactory.getSession().createQuery(lsql);
        List<T> results = query.list();
        if (results.size() <= 0) {
            return null;
        }
        return results;
    }

    private String getClassNameOnly(Class c) {
        return c.getName().substring(c.getName().lastIndexOf(".") + 1);
    }
}
